package com.vite.web.controller.system;

import com.vite.common.config.ViteConfig;
import com.vite.common.constant.Constants;
import com.vite.common.constant.UserConstants;
import com.vite.common.core.domain.AjaxResult;
import com.vite.common.core.domain.entity.SysMenu;
import com.vite.common.core.domain.entity.SysUser;
import com.vite.common.core.domain.model.LoginBody;
import com.vite.common.core.domain.model.LoginUser;
import com.vite.common.utils.DateUtils;
import com.vite.common.utils.SecurityUtils;
import com.vite.common.utils.StringUtils;
import com.vite.framework.web.service.SysLoginService;
import com.vite.framework.web.service.SysPermissionService;
import com.vite.framework.web.service.TokenService;
import com.vite.system.service.ISysConfigService;
import com.vite.system.service.ISysMenuService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * 登录验证
 */
@Tag(name = "登录验证")
@RequiredArgsConstructor
@RestController
public class SysLoginController {

    private final SysLoginService loginService;

    private final ISysMenuService menuService;

    private final SysPermissionService permissionService;

    private final TokenService tokenService;

    private final ISysConfigService configService;

    /**
     * 登录方法
     * 
     * @param loginBody 登录信息
     * @return 结果
     */
    @Operation(summary = "登录方法")
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody) {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.login(
                loginBody.getUsername(),
                loginBody.getPassword(),
                loginBody.getCode(),
                loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    /**
     * 获取用户信息
     * 
     * @return 用户信息
     */
    @Operation(summary = "获取用户信息")
    @GetMapping("getInfo")
    public AjaxResult getInfo() {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser user = loginUser.getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        if (!loginUser.getPermissions().equals(permissions)) {
            loginUser.setPermissions(permissions);
            tokenService.refreshToken(loginUser);
        }
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        ajax.put("validMessage", isValidModifyPwd(user.getPwdUpdateDate()));
        return ajax;
    }

    /**
     * 密码修改提示
     * @param pwdUpdateDate 最后修改密码日期
     * @return 提示信息
     */
    public String isValidModifyPwd(Date pwdUpdateDate) {
        //检查是否初始密码
        if(ViteConfig.isInitPasswordEnable() && StringUtils.isNull(pwdUpdateDate)){
            return UserConstants.PASSWORD_PROMPT_MESSAGE;
        }
        //检查密码是否过期
        int passwordExpireDay = ViteConfig.getPasswordExpireDay();
        if (passwordExpireDay > 0) {
            Date nowDate = DateUtils.getNowDate();
            if (StringUtils.isNull(pwdUpdateDate)
                    || DateUtils.differentDaysByMillisecond(nowDate, pwdUpdateDate) > passwordExpireDay) {
                // 如果从未修改过初始密码，直接提醒过期
                return UserConstants.PASSWORD_EXPIRE_MESSAGE;
            }
        }
        return null;
    }


    /**
     * 获取路由信息
     * 
     * @return 路由信息
     */
    @Operation(summary = "获取路由信息")
    @GetMapping("getRouters")
    public AjaxResult getRouters() {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return AjaxResult.success(menuService.buildMenus(menus));
    }
}
